# -*- coding: utf-8 -*-
__author__ = 'Paul'
from five import grok
from plone.app.layout.viewlets.interfaces import IAboveContent
from plone.app.layout.globals.interfaces import IViewView
from Products.bpTheme.interfaces import IBpTheme
from zope.interface import Interface
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from plone.app.layout.globals.interfaces import IViewView
from Products.ATContentTypes.interface import IATFolder
from zope.site.hooks import getSite
from zope.component import getMultiAdapter
from OFS.interfaces import IOrderedContainer
from Products.bpTheme.interfaces import IInteresesNavManager
import random
from Products.bpTheme.viewlets.grokLayer import GrokLayer


class interesesNavBase(grok.Viewlet):
    grok.baseclass()
    grok.context(Interface)

    grok.require('zope2.View')
    grok.template('interesesNav_template')


    def update(self):
        pass

    def getNav(self):
        listado= self._data()
        if not listado:
            return None
        rex=[]
        for avi in listado:
            selected="noselected"
            if avi.id != 'intereses':
                if avi.id in self.context.getPhysicalPath():
                    selected="selected"
                rex.append({"title":avi.Title,
                            "url":avi.getPath(),
                            "descri":avi.Description[:150],
                            "selected":selected,
                            "id":avi.id,
                            "randUrl":self.getRandomUrl(avi.getObject()),
                            "position":self.get_position_in_parent(avi.getObject())})
        return  sorted(rex, key=lambda k: k['position'])

    def getRandomUrl(self,carpeta):
        """Dada una carpeta devuelve un lista"""
        listaIdsX=carpeta.objectIds()
        if "syndication_information" in listaIdsX:
            listaIdsX.remove("syndication_information")
        if len(listaIdsX)>0:
            return carpeta[listaIdsX[random.randrange(0,len(listaIdsX))]].absolute_url()
        else:
            return None


    def _data(self):
        plone_tools         = getMultiAdapter((self.context, self.request), name=u'plone_tools')
        catalog             = plone_tools.catalog()
        home                = getSite()
        try:
            folderAvisos        = home["home"]["intereses"]
            ffPath              = '/'.join(folderAvisos.getPhysicalPath())
            query               = dict(portal_type=("Folder","Products.bpContents.directorio",))
            query['sort_on']    = 'modified'
            query['path']       = {'query' : ffPath, 'depth' : 1 }
            result=catalog(query)
            return result
        except :
            return  None

    def get_position_in_parent(self,obj):
        """
        Use IOrderedContainer interface to extract the object's manual ordering position
        """
        parent = obj.aq_inner.aq_parent
        ordered = IOrderedContainer(parent, None)
        if ordered is not None:
            return ordered.getObjectPosition(obj.getId())
        return 0

    def sort_by_position(self,a, b):
        """
        Python list sorter cmp() using position in parent.
        Descending order.
        """
        return self.get_position_in_parent(a) - self.get_position_in_parent(b)


class InteresesNav(interesesNavBase):
    grok.name("interesesNav")
    grok.viewletmanager(IAboveContent)